<?php

namespace App\Http\Controllers;

use Houdunwang\WeChat\WeChat;
use Illuminate\Http\Request;
use Modules\Weixin\Entities\WxConfig;
use Modules\Weixin\Entities\WxKeywords;
use Modules\Weixin\Entities\WxRule;

class WeixinController extends Controller
{
    public function handle(WxConfig $wxConfig){
    	$this->valid ($wxConfig);
		$instance =WeChat::instance('message');
		//判断是否是文本消息
		if ($instance->isTextMsg())
		{
			$message  = $instance->Content;
			return $this->respons($message);
		}
	}
	public function valid($wxConfig){
		$config=include base_path ('config').'/wxconfig.php';
		$wconfig=$wxConfig->pluck('value','name')->toArray();
		$config=array_merge ($config,$wconfig);
		WeChat::config ($config)->valid();
	}
	//回复用户消息
	public function respons($message){
    	if($wxkey=WxKeywords::where('key',$message)->first()){
    		$rule=WxRule::find($wxkey['rule_id']);
    		$class='\Modules\\'.$rule['module'].'\Respons';
			//通过回调方法找到对应类的对应方法来处理微信回复
			return call_user_func_array([new $class, 'handle'], [$rule]);
		}
	}
}
